package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.gulimall.auth.feign.MemberFeignClient;
import com.atguigu.common.vo.MemberResponseVo;
import com.atguigu.gulimall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理社交登录
 */
@Slf4j
@Controller
public class OAuth2Controller {
    @Autowired
    private MemberFeignClient memberFeignClient;

    //https://api.weibo.com/oauth2/access_token?client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=authorization_code&redirect_uri=YOUR_REGISTERED_REDIRECT_URI&code=CODE
    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code , HttpSession session) {
        Map<String, String> map = new HashMap<>();
        map.put("client_id", "1178800107");
        map.put("client_secret", "f059e8cffb6956b7d74a8240a84da80a");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code", code);
        try {
            HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(), new HashMap<>(), map);
            System.out.println(response);
            if (response.getStatusLine().getStatusCode() == 200) {
                String s = EntityUtils.toString(response.getEntity());
                SocialUser socialUser = JSONObject.parseObject(s, SocialUser.class);
                //可以拿到token .   第一次进 自动注册
                R authUer = memberFeignClient.authLogin(socialUser);
                if (authUer.getCode() == 0) {
                    MemberResponseVo memberResponse = authUer.getData("data", new TypeReference<MemberResponseVo>() {
                    });
                    log.info("登录的信息{}", memberResponse);
                    session.setAttribute(AuthServerConstant.LOGIN_USER,memberResponse);
                    return "redirect:http://gulimall.com";
                }
                //重定向到首页
                return "redirect:http://gulimall.com";
            } else {
                return "redirect:hhtp://auth.gulimall.com/login.html";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}

